/************************************************************************

								Heroes IV
					  Copyright 2000, The 3DO Company

	------------------------------------------------------------------
  						       abbreviate_number.h

	$Header: /game/abbreviate_number.h $

	$NoKeywords: $

 ************************************************************************/

// kill the 255+ character identifier warning.  Templates tend to exceed that easily.
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "abbreviate_number.h"

#include "font.h"
#include "format_string.h"

static std::string insert_commas( int arg )
{
	std::string result;

	while (arg >= 1000)
	{
		result = "," + format_string( "%03i", arg % 1000 ) + result;
		arg /= 1000;
	}
	if (arg > 0 || result.empty())
		result = format_string( "%i", arg ) + result;
	return result;
}

char const* const   k_unit_symbols[] = { "", "k", "M", "G" };

// abbreviate a number to a certain width, and include comma separators
std::string abbreviate_number( int arg, int character_limit )
{
	std::string	sign;
	std::string	result;
	int			i;

	if (arg < 0)
	{
		sign = "-";
		arg = -arg;
	}
	for (i = 0; i < 3; ++i)
	{
		result = sign + insert_commas( arg ) + k_unit_symbols[i];
		if (arg < 1000 || (int)result.length() <= character_limit)
			return result;
		arg /= 100;
		result = sign + insert_commas( arg / 10 ) + "." + format_string( "%i", arg % 10 )
			   + k_unit_symbols[i + 1];
		if ((int)result.length() <= character_limit)
			return result;
		arg /= 10;
	}
	return sign + insert_commas( arg ) + k_unit_symbols[i];
}

// abbreviate a number to a certain width, and include comma separators
std::string abbreviate_number( int arg, t_font const& font, int width )
{
	std::string	sign;
	std::string	result;
	int			i;

	if (arg < 0)
	{
		sign = "-";
		arg = -arg;
	}
	for (i = 0; i < 3; ++i)
	{
		result = sign + insert_commas( arg ) + k_unit_symbols[i];
		if (arg < 1000 || font.get_width( result.c_str() ) <= width)
			return result;
		arg /= 100;
		result = sign + insert_commas( arg / 10 ) + "." + format_string( "%i", arg % 10 )
			   + k_unit_symbols[i + 1];
		if (font.get_width( result.c_str() ) <= width)
			return result;
		arg /= 10;
	}
	return sign + insert_commas( arg ) + k_unit_symbols[i];
}
